import React, { useRef, forwardRef, useImperativeHandle } from 'react';
import { cloneDeep } from 'lodash';
import { Form, Input, Select, Radio, Tag } from '@block/plug';
import { $fetch } from '@block/utils';
import { CollapseList } from '@src/components';
import { getUUid, RiskLevel } from '@src/utils';
import {
  EFFICIENCY_SPACE_TEXT,
  NORMAL_MAX_LENGTH,
  PROGRESS_LIST_MAX,
  PROGRESS_MAX_LENGTH,
  PROGRESS_TEXT,
  EFFICIENCY_SPACE_MAX_LENGTH,
} from '../../constant';
import { AuditProgressItem } from '../../types';

import './AuditProblemProgress.scss';
import Url from '../../url';

interface Props extends DefaultToEditItem {
  value?: AuditProgressItem[];
  onChange?: (val: AuditProgressItem[]) => void;
  mode?: Mode;
  riskGradeList: SelectOption[];
}

interface Handle {
  /** 表单校验 */
  onValidate: () => boolean;
}

/**
 * 重点审计发现及整改进度
 */
const AuditProblemProgress = forwardRef<Handle, Props>((props, ref) => {
  const { value, onChange, mode, riskGradeList = [] } = props;

  /** 头部表单Form */
  const contentFormListRef = useRef<Array<Form>>([]);
  /** 内容表单Form */
  const headerFormListRef = useRef<Array<Form>>([]);

  const getAddInitData = (): Partial<AuditProgressItem> => ({
    problemAndProgressId: getUUid('string') as string,
  });

  /**
   * 列表change事件
   * @param val 新列表值
   */
  const handleListChange = (val: AuditProgressItem[]) => {
    onChange?.(val);
  };

  /**
   * 表单change事件
   * @param key formItemKey
   * @param val item值
   * @param index 下标
   */
  const handleFormChange = (key: string, val, index: number) => {
    const newDataList = cloneDeep(value);
    newDataList[index] = { ...(newDataList?.[index] ?? {}), [key]: val };
    onChange?.(newDataList);
  };

  const handleValidate = () => {
    let validate = true;
    headerFormListRef.current?.forEach((formRef) => {
      if (formRef) {
        const headerValidate = formRef?.validateFields();
        if (validate && !headerValidate) validate = false;
      }
    });
    contentFormListRef.current?.forEach((formRef) => {
      if (formRef) {
        const contentValidate = formRef?.validateFields();
        if (validate && !contentValidate) validate = false;
      }
    });
    return validate;
  };

  useImperativeHandle(ref, () => ({ onValidate: handleValidate }));

  const getContainer = (): HTMLElement => document.querySelector('.project-detail-content') || document.body;

  /** 风险等级view态颜色 */
  const renderRiskLevel = (riskLevelValue: RiskLevel) => {
    switch (riskLevelValue) {
      case RiskLevel.high:
        return <Tag theme="red">高风险</Tag>;
      case RiskLevel.medium:
        return <Tag theme="orange">中风险</Tag>;
      case RiskLevel.low:
        return <Tag theme="green">低风险</Tag>;
      default:
        return '-';
    }
  };

  const renderCardHeadSelect = (val: AuditProgressItem, index: number) => {
    const { businessProcess } = val ?? {};
    return (
      <Form
        className="audit-appendix-header-form"
        ref={(formRef: Form) => {
          headerFormListRef.current[index] = formRef;
        }}
        defaultFieldsValue={{ businessProcess }}
        mode={mode}
        onFieldValueChange={(formKey, formVal) => handleFormChange(formKey, formVal, index)}
      >
        <Form.Item
          formItemKey="businessProcess"
          label="审计领域："
          rules={[
            { required: true, whitespace: true, message: '请输入审计领域：' },
            { max: NORMAL_MAX_LENGTH, message: `不允许超过${NORMAL_MAX_LENGTH}字符` },
          ]}
        >
          {({ value: businessProcessValue }) => {
            if (mode === 'edit' || businessProcessValue?.length > 0) {
              return (
                <Input
                  toFormItem
                  dispatchChange={['onInput']}
                  placeholder={`输入不超过${NORMAL_MAX_LENGTH}字符`}
                  showCount
                  maxLength={NORMAL_MAX_LENGTH}
                />
              );
            }
            return '-';
          }}
        </Form.Item>
      </Form>
    );
  };

  const renderCardContent = (val: AuditProgressItem, index: number) => {
    const { problemDesc, efficiencySpace, riskLevel, problemTypeList, businessFeedback, auditFollowUp } = val ?? {};
    return (
      <Form
        ref={(formRef: Form) => {
          contentFormListRef.current[index] = formRef;
        }}
        defaultFieldsValue={{
          problemDesc,
          efficiencySpace,
          riskLevel,
          problemTypeList,
          businessFeedback,
          auditFollowUp,
        }}
        mode={mode}
        labelWidth="8em"
        onFieldValueChange={(formKey, formVal) => handleFormChange(formKey, formVal, index)}
      >
        <Form.Item
          formItemKey="problemDesc"
          label="问题描述："
          rules={{ required: true, whitespace: true, message: '请填写问题描述' }}
        >
          {({ value: problemDescValue }) => {
            if (mode === 'edit' || problemDescValue?.length > 0) {
              return (
                <Input.TextArea
                  toFormItem
                  dispatchChange={['onInput']}
                  maxLength={PROGRESS_MAX_LENGTH}
                  showCount
                  placeholder={`输入不超过${PROGRESS_MAX_LENGTH}字符`}
                  autosize={{ minRows: 5 }}
                />
              );
            }
            return '-';
          }}
        </Form.Item>
        <Form.Item
          formItemKey="efficiencySpace"
          label="可提效空间："
          rules={{ required: true, whitespace: true, message: '请填写可提效空间' }}
        >
          {({ value: efficiencySpaceValue }) => {
            if (mode === 'edit' || efficiencySpaceValue?.length > 0) {
              return (
                <Input
                  toFormItem
                  dispatchChange={['onInput']}
                  maxLength={EFFICIENCY_SPACE_MAX_LENGTH}
                  showCount
                  placeholder={EFFICIENCY_SPACE_TEXT}
                />
              );
            }
            return '-';
          }}
        </Form.Item>
        <Form.Item formItemKey="riskLevel" label="风险等级：" required message="请选择风险等级">
          {({ value: riskLevelValue }) => {
            if (mode === 'edit') {
              return (
                <Radio.Group toFormItem>
                  {riskGradeList?.map((grade) => (
                    <Radio key={grade?.code} value={grade?.code}>
                      {grade?.name}
                    </Radio>
                  ))}
                </Radio.Group>
              );
            }
            return renderRiskLevel(riskLevelValue);
          }}
        </Form.Item>
        <Form.Item formItemKey="problemTypeList" label="问题分类：" required message="请填写问题分类">
          {({ value: problemTypeListValue }) => {
            if (mode === 'edit' || problemTypeListValue?.length > 0) {
              return (
                <Select
                  toFormItem
                  placeholder="请选择问题分类"
                  keyField="code"
                  labelField="name"
                  filterable={false}
                  popLayer={{ getContainer }}
                  multiple
                  onFetchData={(search) => {
                    return $fetch(Url.queryProblemTypeList, {
                      search: search?.trim(),
                    });
                  }}
                />
              );
            }
            return '-';
          }}
        </Form.Item>
        <Form.Item
          formItemKey="businessFeedback"
          label="业务方反馈："
          rules={{ required: true, whitespace: true, message: '请填写业务方反馈' }}
        >
          {({ value: businessFeedbackValue }) => {
            if (mode === 'edit' || businessFeedbackValue?.length > 0) {
              return (
                <Input.TextArea
                  toFormItem
                  dispatchChange={['onInput']}
                  maxLength={PROGRESS_MAX_LENGTH}
                  showCount
                  placeholder={`输入不超过${PROGRESS_MAX_LENGTH}字符`}
                  autosize={{ minRows: 5 }}
                />
              );
            }
            return '-';
          }}
        </Form.Item>
        <Form.Item
          formItemKey="auditFollowUp"
          label="审计跟进："
          rules={{ required: true, whitespace: true, message: '请填写审计跟进' }}
        >
          {({ value: auditFollowUpValue }) => {
            if (mode === 'edit' || auditFollowUpValue?.length > 0) {
              return (
                <Input.TextArea
                  toFormItem
                  dispatchChange={['onInput']}
                  maxLength={PROGRESS_MAX_LENGTH}
                  showCount
                  placeholder={`输入不超过${PROGRESS_MAX_LENGTH}字符`}
                  autosize={{ minRows: 5 }}
                />
              );
            }
            return '-';
          }}
        </Form.Item>
      </Form>
    );
  };
  return (
    <div className="audit-problem-progress">
      <div className="audit-problem-progress-text">{PROGRESS_TEXT}</div>
      <CollapseList<Partial<AuditProgressItem>>
        className="audit-problem-progress-collapse"
        title={(val, index) => `重点业务发现${index + 1}`}
        // @ts-expect-error
        defaultValue={[0]}
        multiple
        maxLength={PROGRESS_LIST_MAX}
        expandIconPosition="end"
        addInitData={getAddInitData}
        deleteDisable={(val, index, dataList) => dataList?.length <= 1}
        data={value}
        keyField="problemAndProgressId"
        mode={mode}
        onChange={handleListChange}
        renderHeaderSelect={renderCardHeadSelect}
        renderContent={renderCardContent}
        getContainer={getContainer}
      />
    </div>
  );
});

export default AuditProblemProgress;
